//
//  BookDetailViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/4.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "BookDetailViewController.h"
#import "BookHeaderTableViewCell.h"
#import "BookFooterTableViewCell.h"
#import "BookReadingViewController.h"
#import "LoginViewController.h"
#import "RegistViewController.h"

@interface BookDetailViewController () <UITableViewDelegate, UITableViewDataSource, LoginDelegate>

/** 图书详情列表 */
@property (nonatomic, strong) UITableView * detailTableView;
/** 图书详情数据源 */
@property (nonatomic, strong) NSDictionary * bookDetailDic;
/** 下载完成弹窗 */
@property (nonatomic, strong) UIView * overAlert;
/** 书籍本地路径 */
@property (nonatomic, copy) NSString * filePath;
/** BookReadingVC */
@property (nonatomic, strong) BookReadingViewController * bookReadingVC;


@end

@implementation BookDetailViewController

#pragma mark - lazy load

- (BookReadingViewController *)bookReadingVC{
    if (!_bookReadingVC) {
        _bookReadingVC = [[BookReadingViewController alloc] init];
        _bookReadingVC.filePath = [[self.filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"meimeng"];
    }
    return _bookReadingVC;
}

- (UIView *)overAlert{
    if (!_overAlert) {
        _overAlert = [[UIView alloc] initWithFrame:self.view.bounds];
        _overAlert.backgroundColor = COLOR_alphaBGCOLOR;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(97), HeightScale(250), WidthScale(220), HeightScale(157))];
        imageView.image = ImageNamed(@"xiazaiwancheng");
        
        [_overAlert addSubview:imageView];
    }
    return _overAlert;
    
}

- (UITableView *)detailTableView{
    if (!_detailTableView) {
        _detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStyleGrouped];
        _detailTableView.delegate = self;
        _detailTableView.dataSource = self;
        _detailTableView.bounces = NO;
        _detailTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        if (@available(iOS 11.0, *)) {
            _detailTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _detailTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"详情";
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    
    
    
    
    //添加统计
    [self requestStatistics];
    
    [self requestBookDetail];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [AppDelegate shareDelegate].tabBar.customBar.center = CGPointMake(SCREEN_W / 2, SCREEN_H + [AppDelegate shareDelegate].tabBar.customBar.frame.size.height / 2);
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [Tool setNavigationBarType:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - UITableViewDelegate & UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BookHeaderTableViewCell *cell = [[BookHeaderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        
        
        [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.bookDetailDic[@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershuji")];
        cell.titleLabel.text = [NSString stringWithFormat:@"【%@】", self.bookDetailDic[@"name"]];
        cell.authorNameLabel.text = [NSString stringWithFormat:@"%@", [self.bookDetailDic[@"author"] length] ? self.bookDetailDic[@"author"] : @"连环画"];
        
        cell.timeLabel.text = [Tool dateConvert:[NSString stringWithFormat:@"%@", self.bookDetailDic[@"publishTime"]]];
        
        cell.houseLabel.text = [NSString stringWithFormat:@"%@", self.bookDetailDic[@"publisher"]];

        if ([self alreadyExist]) {
            //已下载
            [cell.readButton setImage:ImageNamed(@"开始阅读") forState:UIControlStateNormal];
            cell.downloadButton.hidden = YES;
        }
        
        [cell.downloadButton addTarget:self action:@selector(downloadBook:) forControlEvents:UIControlEventTouchUpInside];
        [cell.readButton addTarget:self action:@selector(readButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    } else {
        BookFooterTableViewCell *cell = [[BookFooterTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        
        cell.sizeLabel.text = [NSString stringWithFormat:@"%@页", self.bookDetailDic[@"pages"]];
        cell.descTextView.text = [NSString stringWithFormat:@"        %@", self.bookDetailDic[@"summaryText"] ? : @""];
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return HeightScale(530);
    } else {
        return HeightScale(200);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return HeightScale(5);
    }
    return 0.00001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - 事件处理

- (void)readButtonClicked:(UIButton *)button{
    if (![AppDelegate shareDelegate].userModel) {
        //未登录
        [self loginPresent];
    } else {
        [SVProgressHUD show];
        BookHeaderTableViewCell *cell = (BookHeaderTableViewCell *)[[button superview] superview];
        if (cell.downloadButton.hidden) {
            DLog(@"已下载，本地阅读");
            self.bookReadingVC.filePath = self.filePath;
            self.bookReadingVC.pages = [self.bookDetailDic[@"pages"] integerValue];
            self.bookReadingVC.dataDic = self.bookDetailDic;
            self.bookReadingVC.isMagazine = NO;
            [self.bookReadingVC readDataSource];
            self.bookReadingVC.native = YES;
        } else {
            DLog(@"在线阅读");
            self.bookReadingVC.isMagazine = NO;
            self.bookReadingVC.dataDic = self.bookDetailDic;
            self.bookReadingVC.filePath = self.bookDetailDic[@"filePath"];
            self.bookReadingVC.pages = [self.bookDetailDic[@"pages"] integerValue];
        }
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.bookReadingVC];
        nav.navigationBar.hidden = YES;
        [self presentViewController:nav animated:YES completion:^{
            [SVProgressHUD dismiss];
        }];
    }
}

- (void)loginSuccess{
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
    
    NSDictionary *userDic = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    
    [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:userDic];
    
    DLog(@"%@", [AppDelegate shareDelegate].userModel.userId);
}

#pragma mark - 查看本地是否有这本书

- (BOOL)alreadyExist{
    //本地书籍
    NSArray *nativeBookArr =  [[NSFileManager defaultManager] contentsOfDirectoryAtPath:BooksPath error:nil];
    
    for (NSString *bookName in nativeBookArr) {
        if ([bookName isEqualToString:self.bookDetailDic[@"name"]]) {
            self.filePath = [BooksPath stringByAppendingPathComponent:self.bookDetailDic[@"name"]];
            return YES;
        }
    }
    return NO;
}

#pragma mark - 登录

- (void)loginPresent{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.delegate = self;
    [self presentViewController:loginVC animated:YES completion:nil];
}

- (void)registPresent{
    RegistViewController *registVC = [[RegistViewController alloc] init];
    [self presentViewController:registVC animated:YES completion:nil];
}

#pragma mark - data request

/** 书籍详情 */
- (void)requestBookDetail{
    NSString *URL = [NSString stringWithFormat:KBookDetail, KHostAddress, self.bookDic[@"id"]];
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            self.bookDetailDic = [responseObject objectForKey:@"data"];
            
            [self alreadyExist];
            
            [self.view addSubview:self.detailTableView];
            
            [self requestHistory];
            
        }
        
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

/** 下载书籍 */
- (void)downloadBook:(UIButton *)button{
    
    if (![AppDelegate shareDelegate].userModel) {
        //未登录
        [self loginPresent];
        
    } else {
        //已登录
        BookHeaderTableViewCell *cell = (BookHeaderTableViewCell *)[[button superview] superview];
        
        //透明色视图遮挡屏幕，屏蔽下载过程中，用户进行其他操作。
        UIView *backView = [[UIView alloc] initWithFrame:self.view.bounds];
        backView.backgroundColor = COLOR_CLEAR;
        [[AppDelegate shareDelegate].window addSubview:backView];
        
        //显示下载进度条
        cell.progressView.hidden = NO;
        
        //开始下载请求
        NSString *bookZipURL = [NSString stringWithFormat:@"%@%@.zip", KHostAddress, self.bookDetailDic[@"filePath"]];
        [ZRRequestManager downLoadWithURL:bookZipURL progress:^(NSProgress *progress) {
            
            //获取下载进度百分比
            float value = 1.0 * progress.completedUnitCount / progress.totalUnitCount;
            //子线程中刷新下载进度条进度
            dispatch_async(dispatch_get_main_queue(), ^{
                cell.progressView.progress = value;
            });
            
            DLog(@"下载进度 -- %.1lf%%", 100.0 * value);
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            //下载文件目标路径
            
            NSString *bookPath = [BooksPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.zip", self.bookDetailDic[@"name"]]];
            self.filePath = [bookPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            
            return [NSURL fileURLWithPath:self.filePath];
            
        } downLoadSuccess:^(NSURLResponse *response, NSURL *filePath) {
            
            //移除透明色视图遮挡
            [backView removeFromSuperview];
            
            //隐藏下载进度条
            cell.progressView.hidden = YES;
            
            //显示下载完成弹窗(1s后自动消失)
            [[AppDelegate shareDelegate].window addSubview:self.overAlert];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.overAlert removeFromSuperview];
            });
            
            //“在线阅读”换成“开始阅读”
            [cell.readButton setImage:ImageNamed(@"开始阅读") forState:UIControlStateNormal];
            //下载完成，隐藏下载按钮
            cell.downloadButton.hidden = YES;
            
            
            DLog(@"%@", filePath);
            
            //解压zip
            [SSZipArchive unzipFileAtPath:self.filePath toDestination:[self.filePath stringByDeletingPathExtension] progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
                nil;
            } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nonnull error) {
                //解压完成后，删除沙盒中的zip文件，只保留已解压的书刊。
                [[NSFileManager defaultManager] removeItemAtPath:self.filePath error:nil];
                self.filePath = [self.filePath stringByDeletingPathExtension];
            }];
            
            //添加到书架
            
            [self requestAddShelf];
            
        } failure:^(NSError *error) {
            [ZRProgressHUD showMsgWithoutView:@"下载失败，请稍后重试"];
            [backView removeFromSuperview];
            cell.progressView.hidden = YES;
            DLog(@"%@", error);
        }];
    }
}

/** 添加浏览历史 */
- (void)requestHistory{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        
        NSString *URL = [NSString stringWithFormat:KaddHistory, KHostAddress, self.bookDic[@"id"], @(1), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            DLog(@"添加浏览历史");
        } failure:^(NSError *error) {
            DLog(@"添加浏览历史失败");
        }];
    }
}

/** 添加到书架 */
- (void)requestAddShelf{
    if ([AppDelegate shareDelegate].userModel) {
        NSString *URL = [NSString stringWithFormat:KaddShelf, KHostAddress, self.bookDic[@"id"], @(1), KOrganizationID, [AppDelegate shareDelegate].userModel.userId];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加书架成功");
            } else {
                DLog(@"添加书架失败");
            }
            
            
        } failure:^(NSError *error) {
            DLog(@"添加书架失败");
        }];
    }
}

/** 添加统计 */
- (void)requestStatistics{
    //判断是否登录
    if ([AppDelegate shareDelegate].userModel) {
        //1、图书；2、视频；3、音频；4、期刊杂志5、县域视频6、资讯
        NSString *URL = [NSString stringWithFormat:Kstatistics, KHostAddress, KCurrentIP, [AppDelegate shareDelegate].userModel.userId, KOrganizationID, @(1), self.bookDic[@"id"]];
        [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                DLog(@"添加统计成功");
            } else {
                DLog(@"添加统计失败");
            }
        } failure:^(NSError *error) {
            DLog(@"%@", error);
        }];
    }
}

@end
